//
//  CurrencyExchangeView.swift
//  Exchange
//
//  Created by 孟祥群 on 2018/4/26.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit

class CurrencyExchangeView: BaseView, UITableViewDelegate, UITableViewDataSource, CAAnimationDelegate, SelectmangerDelegate{
    var viewModel:CurrencyExchangeViewModel?
    var controller:CurrencyOrderViewController?
    var buyBtnArr:NSMutableArray = []
    lazy var tableView:UITableView = {
        let tableView = UITableView(frame: CGRect.zero, style: UITableViewStyle.plain)
        tableView.separatorStyle = UITableViewCellSeparatorStyle.none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.isScrollEnabled = false
        tableView.themeBackground = ThemeManager.ThemeColorKeys.background
        return tableView
    }()
    lazy var headView: UIView = {
       let view = UIView(frame: CGRect(x: 0, y: 0, width: kSCREEN_WIDTH, height: 370))
       return view
    }()
    
    lazy var buyBtn: UIButton = {
       let btn = UIButton()
       btn.layer.cornerRadius = 11
       btn.layer.masksToBounds = true
       btn.backgroundColor = kGreenColor
        btn.addTarget(self, action: #selector(buyBtnAction), for: UIControlEvents.touchUpInside)
       btn.themeSetTitleColor(ThemeManager.ThemeColorKeys.btnText, for: UIControlState.normal)
       btn.setTitle(kText("买入"), for: UIControlState.normal)
       btn.titleLabel?.font = UIFont.systemFont(ofSize: 13)
       return btn
    }()
    
    lazy var sellBtn: UIButton = {
        let btn = UIButton()
        btn.layer.cornerRadius = 11
        btn.layer.masksToBounds = true
        btn.backgroundColor = UIColor.clear
        btn.themeSetTitleColor(ThemeManager.ThemeColorKeys.text2, for: UIControlState.normal)
        btn.addTarget(self, action: #selector(sellAction), for: UIControlEvents.touchUpInside)
        btn.setTitle(kText("卖出"), for: UIControlState.normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 13)
        return btn
    }()
    
    lazy var limitBtn: CustomBtn = {
        let btn  = CustomBtn(style: placeStyle.styleLeft)
        btn.nameLabel.text = kText("限价")
        btn.nameLabel.font = UIFont.systemFont(ofSize: 13)
        btn.addTarget(self, action: #selector(priceKindAction), for: UIControlEvents.touchUpInside)
        btn.nameLabel.themeTextColor = ThemeManager.ThemeColorKeys.text2
        btn.photoImageView.image = UIImage(named: "selectArrow")
        return btn
    }()
    
    lazy var changeView:ExchangeView = {
        let view = ExchangeView()
        view.textField.keyboardType = UIKeyboardType.decimalPad
        view.textField.delegate = self
        view.subBtn.setImage(UIImage(named: "coinMinus"), for: UIControlState.normal)
        view.addBtn.setImage(UIImage(named: "coinAdd"), for: UIControlState.normal)
        view.addBtn.addTarget(self, action: #selector(addBtnAction), for: UIControlEvents.touchUpInside)
        view.subBtn.addTarget(self, action: #selector(subBtnAction), for: UIControlEvents.touchUpInside)
        view.textField.addTarget(self, action: #selector(textFieldDidChangeValue(textField:)), for:UIControlEvents.editingChanged)
        return view
    }()
    
    //价格最优提示
    lazy var optimalLabel:UILabel = {
        let label = UILabel()
        label.isHidden = true
        label.themeBackground = ThemeManager.ThemeColorKeys.background4
        label.text = kText("以当前最优价格成交")
        label.font = UIFont.systemFont(ofSize: 13)
        label.textAlignment = .center
        label.textColor = kLineMoreColor
        label.layer.border =  ThemeManager.ThemeColorKeys.borderColor
        label.layer.borderWidth = 0.5
        return label
    }()
    
    lazy var priceBtn:UIButton = {
        let btn = UIButton()
        btn.addTarget(self, action: #selector(changePriceAction), for: UIControlEvents.touchUpInside)
        btn.themeSetTitleColor(ThemeManager.ThemeColorKeys.text3, for: UIControlState.normal)
        btn.setTitle("0.00", for: UIControlState.normal)
        btn.titleLabel?.font = UIFont(name: "PingFang-SC-Heavy", size: 16)
        return btn
    }()
    
    lazy var moneyBtn:UIButton = {
        let btn = UIButton()
        btn.themeSetTitleColor(ThemeManager.ThemeColorKeys.text3, for: UIControlState.normal)
        if AppCacheInfo.default.currency == "CNY" {
            btn.setTitle("≈¥0.0", for: UIControlState.normal)
            
        }else {
            btn.setTitle("≈$0.0", for: UIControlState.normal)
        }
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 11)
        return btn
    }()
    
    /// 选择按钮
    lazy var selectNumber: SelectNumberView = {
        let select = SelectNumberView()
        select.delegate = self
        return select
    }()

    lazy var currentMoney:UILabel = {
        let moneyLabel = BaseLabel(style: .thirdStyle)
        moneyLabel.font = UIFont.systemFont(ofSize: 11)
        return moneyLabel
    }()
    
    lazy var numberView:ExchangeView = {
        let view = ExchangeView()
        view.textField.keyboardType = UIKeyboardType.decimalPad
        view.subBtn.isHidden = true
        view.textField.delegate = self
        view.textField.addTarget(self, action: #selector(textFieldDidChangeValue(textField:)), for:UIControlEvents.editingChanged)
        view.textField.placeholder = kText("数量")
        view.textField.setPlaceholderColor()
        view.textField.textAlignment = NSTextAlignment.left
        view.addBtn.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        view.addBtn.themeSetTitleColor(ThemeManager.ThemeColorKeys.text2, for: UIControlState.normal)
        
        return view
    }()
    
   lazy var showLabel:UILabel = {
       let label = UILabel()
        label.frame = CGRect(x: 0, y: 0, width: 100,height: 20)
        return label
    }()
    
    lazy var approveLabel:UILabel = {
        let label = BaseLabel(style: .twiceStyle)
        label.font = UIFont.systemFont(ofSize: 12)
        return label
    }()
    
    lazy var nuberLabel: UILabel = {
        let label = UILabel()
        label.textColor = kTextColor
        label.font = UIFont.systemFont(ofSize: 9)
        label.text = "0"
        return label
    }()
    
    lazy var kindPrice: UILabel = {
        let label = BaseLabel(style: .twiceStyle)
        label.font = UIFont.systemFont(ofSize: 9)
        return label
    }()
    
    lazy var tradeLabel: UILabel = {
        let label = BaseLabel(style: .twiceStyle)
        label.font = UIFont.systemFont(ofSize: 13)
        label.text = "交易额---"
        return label
    }()
    
    lazy var riseBtn: UIButton = {
        let btn = UIButton()
        btn.backgroundColor = kGreenColor
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        btn.addTarget(self, action: #selector(riseBtnAction), for: UIControlEvents.touchUpInside)
        return btn
    }()
    
    lazy var footView: UIView = {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: kSCREEN_WIDTH*0.4, height: 40))
        return view
    }()
    
    lazy var digitBtn: CustomBtn = {
        let btn = CustomBtn(style: placeStyle.styleLeft)
        btn.nameLabel.text = kText("小数位数") + (viewModel?.digit)!
        btn.nameLabel.themeTextColor = ThemeManager.ThemeColorKeys.text2
        btn.addTarget(self, action:#selector(selectDigit), for: UIControlEvents.touchUpInside)
        btn.nameLabel.font = UIFont.systemFont(ofSize: 12)
        btn.isHidden = true
        btn.photoImageView.image = UIImage(named: "selectArrow")
        return btn
    }()
    
    lazy var entrustTableView: UITableView = {
        let tableView = UITableView(frame: CGRect.zero, style: UITableViewStyle.plain)
        tableView.separatorStyle = UITableViewCellSeparatorStyle.none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.themeBackground = ThemeManager.ThemeColorKeys.background
        return tableView
    }()
    
    override func setUpUI() -> Void {
        
        self.viewModel =  dataSource as? CurrencyExchangeViewModel
        //注册监听
        dataSource.addObserver(self, forKeyPath: "refreshBool", options: [.new,.old], context: nil)
        dataSource.addObserver(self, forKeyPath: "assetBool", options: [.new,.old], context: nil)
        dataSource.addObserver(self, forKeyPath: "changePair", options: [.new,.old], context: nil)
        dataSource.addObserver(self, forKeyPath: "coinOrder", options: [.new,.old], context: nil)
        self.addSubview(entrustTableView)
        entrustTableView.tableHeaderView = headView
        entrustTableView.snp.makeConstraints { (make) in
            make.top.equalToSuperview()
            make.left.equalToSuperview()
            make.width.equalTo(kSCREEN_WIDTH)
            make.bottom.equalToSuperview()
        }
        headView.addSubview(buyBtn)
        buyBtn.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(15)
            make.left.equalToSuperview().offset(isiphone5S() ? 10 : 15)
            make.width.equalTo(48)
            make.height.equalTo(22)
        }

        headView.addSubview(sellBtn)
        sellBtn.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(15)
            make.left.equalToSuperview().offset(isiphone5S() ? 55 : 75)
            make.width.equalTo(48)
            make.height.equalTo(22)
        }
       
        buyBtnArr.add(buyBtn)
        buyBtnArr.add(sellBtn)
        
        headView.addSubview(limitBtn)
        limitBtn.position?.exchangePlace(btn: limitBtn)
        limitBtn.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(15)
            make.right.equalToSuperview().offset(-CGFloat(kSCREEN_WIDTH*0.4) - CGFloat(15))
            make.width.equalTo(48)
            make.height.equalTo(22)
        }

        headView.addSubview(changeView)
        changeView.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.width.equalTo(CGFloat(kSCREEN_WIDTH*0.6) - CGFloat(30))
            make.top.equalToSuperview().offset(51)
            make.height.equalTo(40)
        }
        
        headView.addSubview(optimalLabel)
        optimalLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.width.equalTo(CGFloat(kSCREEN_WIDTH*0.6) - CGFloat(30))
            make.top.equalToSuperview().offset(51)
            make.height.equalTo(40)
        }

        headView.addSubview(currentMoney)
        currentMoney.snp.makeConstraints { (make) in
            make.top.equalTo(changeView.snp.bottom).offset(10)
            make.left.equalToSuperview().offset(15)
        }

        headView.addSubview(numberView)
        numberView.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.width.equalTo(CGFloat(kSCREEN_WIDTH*0.6) - CGFloat(30))
            make.top.equalToSuperview().offset(140)
            make.height.equalTo(40)
        }
        
        numberView.textField.snp.remakeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.right.equalTo(numberView.addBtn.snp.left)
            make.top.bottom.equalToSuperview()
        }

        headView.addSubview(approveLabel)
        approveLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.top.equalToSuperview().offset(203)
        }

        headView.addSubview(selectNumber)
        selectNumber.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.width.equalTo(CGFloat(kSCREEN_WIDTH*0.6) - CGFloat(30))
            make.top.equalToSuperview().offset(219)
            make.height.equalTo(40)
        }

        headView.addSubview(nuberLabel)
        nuberLabel.snp.makeConstraints { (make) in
            make.top.equalTo(selectNumber.snp.bottom).offset(3)
            make.left.equalToSuperview().offset(15)
        }

        headView.addSubview(kindPrice)
        kindPrice.snp.makeConstraints { (make) in
            make.centerY.equalTo(nuberLabel)
            make.right.equalTo(-CGFloat(kSCREEN_WIDTH*0.4) - CGFloat(15))
        }

        headView.addSubview(tradeLabel)
        tradeLabel.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(286)
            make.left.equalToSuperview().offset(15)
        }

        headView.addSubview(riseBtn)
        riseBtn.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(310)
            make.left.equalToSuperview().offset(15)
            make.width.equalTo(CGFloat(kSCREEN_WIDTH*0.6) - CGFloat(30))
            make.height.equalTo(40)
        }


        headView.addSubview(tableView)
        tableView.tableFooterView = footView
        tableView.snp.makeConstraints { (make) in
            make.top.bottom.equalToSuperview()
            make.width.equalTo(kSCREEN_WIDTH*0.4)
            make.right.equalToSuperview()
        }
        let right = isiphone5S() ? -15: -5
        footView.addSubview(digitBtn)
        digitBtn.photoImageView.snp.makeConstraints { (make) in
            make.right.equalToSuperview()
            make.centerY.equalToSuperview()
        }
        digitBtn.nameLabel.snp.makeConstraints { (make) in
            make.right.equalTo(digitBtn.photoImageView.snp.left).offset(-5)
            make.centerY.equalToSuperview()
        }
        digitBtn.snp.makeConstraints { (make) in
            make.top.bottom.equalToSuperview()
            make.right.equalToSuperview().offset(right)
            make.width.equalTo(100)

        }
        headView.addSubview(showLabel)
        
//        entrustTableView.creatEmptyView()
    }
    
    
    //MARK: tableViewDelegate
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if tableView.isEqual(self.tableView) {
            return 5
        }else {
            if viewModel?.currentOder.sourceCoin.count != 0 {
                return 1
            }
            return 0
        }
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        if tableView.isEqual(self.tableView) {
        return 2
        }
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if tableView.isEqual(self.tableView) {
            let identy = "identy"
            var cell = tableView.dequeueReusableCell(withIdentifier: identy) as? DiskDataTableViewCell
            if cell == nil {
                cell = DiskDataTableViewCell(style: .default, reuseIdentifier: identy)
                cell?.selectionStyle = .none
               
            }
            cell?.tag = indexPath.section*10+1000+indexPath.row
            
            if indexPath.section == 0 {
                cell?.priceLabel.textColor = kRedColor
                if (self.viewModel?.depModel?.depUpArr.count)! + indexPath.row - 5 >= 0 {
                    let index = (self.viewModel?.depModel?.depUpArr.count)! + indexPath.row - 5
                    let model:DepdetailModel = (self.viewModel?.depModel!.depUpArr[index])!
                    let bigNumber:String = (self.viewModel?.depModel!.depthBigNumber)!
                    cell?.setModel(model: model, isUp: true,bigNumber:bigNumber)
                }else {
                    cell?.priceLabel.text = "--"
                    cell?.numberLabel.text = "--"
                    cell?.backView.frame = CGRect(x: Double(kSCREEN_WIDTH*0.4), y: 0, width: 0, height: 25)
                }
                cell?.diskLabel.text = String(format: "%d", 5-indexPath.row)
            }else {
                cell?.priceLabel.textColor = kGreenColor
                if (self.viewModel?.depModel?.deptDownArr.count)! > indexPath.row {
                    let model:DepdetailModel = (self.viewModel?.depModel!.deptDownArr[indexPath.row])!
                    let bigNumber:String = (self.viewModel?.depModel!.depthBigNumber)!
                    cell?.setModel(model: model, isUp: false,bigNumber:bigNumber)
                }else {
                    cell?.numberLabel.text = "--"
                    cell?.priceLabel.text = "--"
                    cell?.backView.frame = CGRect(x: Double(kSCREEN_WIDTH*0.4), y: 0, width: 0, height: 25)
                }
                cell?.diskLabel.text = String(format: "%d", indexPath.row+1)
            }
        return cell!
        }else {
            let identy = "entrust"
            var cell = tableView.dequeueReusableCell(withIdentifier: identy) as? EntrustTableViewCell
            if cell == nil {
                cell = EntrustTableViewCell(style: .default, reuseIdentifier: identy)
            }
            cell?.delegate = self
            let model = viewModel?.currentOder
            cell?.exchangeOderType(type: .orderEntrust)
            cell?.setModel(model: model!)
            cell?.line.isHidden = true
            return cell!
            
        }
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if tableView.isEqual(self.tableView) {
        return 25
        }
        return 100
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if  tableView.isEqual(self.tableView) {
            if section == 0 {
                return 35
            }
            return 50
        }
            return 60
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        if tableView.isEqual(entrustTableView) {
            let controller = CurrencyDetailsViewController()
            if viewModel?.currentOder.status == 0 || viewModel?.currentOder.status == 1 || viewModel?.currentOder.status == 3
            || viewModel?.currentOder.status == 5 {
                controller.viewModel?.isCurrent = true
            }
            controller.viewModel?.type = .orderCoinHistoryType
            controller.viewModel?.model = (viewModel?.currentOder)!
            self.viewModel?.controller?.navigationController?.pushViewController(controller, animated: true)
            return
        }
        
        
        if limitBtn.nameLabel.text == kText("市价") {
            return
        }
        if tableView.isEqual(self.tableView) {
        let cell = tableView.viewWithTag(indexPath.section*10+1000+indexPath.row) as!DiskDataTableViewCell
        if cell.priceLabel.text == "--" {
           return
        }
        viewModel?.changePrice(price:cell.priceLabel.text!)
            self.creatAnimation(label: cell.priceLabel, priceStr: cell.priceLabel.text!)
        }
        
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if tableView.isEqual(self.tableView) {
        let height = section == 0 ? 35 : 50
        let view:UIView = UIView(frame: CGRect(x: 0, y: 0, width: Int(kSCREEN_WIDTH), height: height))
        if section == 0 {
            let titleArr = [kText("盘口"),kText("价格"),kText("数量")]
            for i in 0..<3 {
                let label = BaseLabel(style: .thirdStyle)
                var right:CGFloat;
              if i == 1 {
                right = isiphone5S() ? -60 : -70
                }else {
                right = isiphone5S() ? -5 : -15
                }
                
                view.addSubview(label)
                label.text = (titleArr as NSArray).object(at: i) as? String
                label.font = UIFont.systemFont(ofSize: 10)
                label.snp.makeConstraints { (make) in
                    if i != 0 {
                        make.right.equalToSuperview().offset(right)
                    }else {
                        make.left.equalToSuperview()
                    }
                    make.top.equalToSuperview().offset(20)
                    make.height.equalTo(10)
                }
            }
        } else {
            view.addSubview(priceBtn)
            priceBtn.snp.makeConstraints { (make) in
                make.top.equalToSuperview().offset(10)
                make.left.equalToSuperview()
            }
            
            view.addSubview(moneyBtn)
            moneyBtn.snp.makeConstraints { (make) in
                make.top.equalToSuperview().offset(28)
                make.left.equalToSuperview()
            }
        }
        
        return view
        }else {
            let view:UIView = UIView(frame: CGRect(x: 0, y: 0, width: Int(kSCREEN_WIDTH), height: 60))
            view.themeBackground = ThemeManager.ThemeColorKeys.background
            let backView = UIView(frame: CGRect(x: 0, y: 10, width: kSCREEN_WIDTH, height: 50))
            backView.themeBackground = ThemeManager.ThemeColorKeys.background
            view.addSubview(backView)
            let allBtn = CustomBtn(style: .styleRight)
            allBtn.addTarget(self, action: #selector(allBtnAction), for: UIControlEvents.touchUpInside)
            allBtn.nameLabel.text = kText("全部")
            allBtn.nameLabel.themeTextColor = ThemeManager.ThemeColorKeys.text2
            allBtn.nameLabel.font = UIFont.systemFont(ofSize: 14)
            allBtn.photoImageView.themeImage = ThemeManager.ThemeImageKeys.coinAll
            backView.addSubview(allBtn)
            allBtn.position?.exchangePlace(btn: allBtn)
            allBtn.snp.makeConstraints { (make) in
                make.right.equalToSuperview()
                make.centerY.equalToSuperview()
                make.width.equalTo(80)
            }
            
            let line = UIView()
            line.themeBackground = ThemeManager.ThemeColorKeys.tabLineColor
            view.addSubview(line)
            line.snp.makeConstraints { (make) in
                make.bottom.equalToSuperview()
                make.left.right.equalToSuperview()
                make.height.equalTo(0.5)
            }
            
            let titleLabel = UILabel()
            titleLabel.text = kText("当前委托")
            titleLabel.themeTextColor = ThemeManager.ThemeColorKeys.text1
            titleLabel.font = UIFont(name: "PingFang-SC-Bold", size: 16)
            backView.addSubview(titleLabel)
            titleLabel.snp.makeConstraints { (make) in
                make.left.equalToSuperview().offset(28)
                make.centerY.equalToSuperview()
            }
            
            let linView = UIView()
            linView.backgroundColor = kThemeColor
            backView.addSubview(linView)
            linView.snp.makeConstraints { (make) in
                make.left.equalToSuperview().offset(15)
                make.centerY.equalToSuperview()
                make.height.equalTo(15)
                make.width.equalTo(3)
            }
            
            return view
        }
    }
    
    /// KVO监听属性
    ///
    /// - Parameters:
    ///   - keyPath: 被监听的属性名
    ///   - object:
    ///   - change:
    ///   - context:
    @objc override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "refreshBool" {
            if (viewModel?.appearFirstBool)! {
                if !(viewModel?.selectStates)! {
                    self.archiveSmallPric()
                }else {
                    self.archiveBigPrice()
                }
                self.changeLegalMoney()
                if  viewModel?.selectPrice.count != 0 {
                    viewModel?.changeFirst(states: false)
                }
            }
            tableView.reloadData()
        }
        if keyPath == "assetBool" {
            let name =  viewModel?.coinNumber()
            approveLabel.text = name
            self.changeLegalMoney()
        }
        
        if keyPath == "changePair" {
            self.changeCoin()
        }
        
        if keyPath == "coinOrder" {
            entrustTableView.reloadData()
            if self.controller != nil {
                if (viewModel?.isNeedRefreshHistory)! {
                    controller?.viewModel?.refreshHistory()
                }
                controller?.viewModel?.refreshOrder(arr: (viewModel?.coinOrderArr)!)
            }
        }
      
    }
    
    @objc func changePriceAction() {
        if viewModel!.currentPairModel.price == 0.00 {
            return
        }
        viewModel?.changePrice(price:(self.priceBtn.titleLabel?.text)!)
        self.creatAnimation(label: priceBtn.titleLabel!, priceStr: (self.priceBtn.titleLabel?.text)!)
    }
    
    func creatAnimation(label:UILabel,priceStr:String) {
        label.layoutIfNeeded()
        let oldfame = label.convert(label.bounds, to: UIApplication.shared.keyWindow)
        showLabel.isHidden = false
        showLabel.text = priceStr
        showLabel.textColor = label.textColor
        let annimation  = CAKeyframeAnimation(keyPath: "position")
        showLabel.frame = CGRect(x: changeView.textField.x, y: changeView.textField.y, width:changeView.textField.frame.size.width , height: 40)
        showLabel.font = UIFont.systemFont(ofSize: isiphone5S() ? 9 : 11)
        annimation.values = [NSValue(cgPoint: CGPoint(x:oldfame.origin.x+oldfame.size.width/2,y:oldfame.origin.y+oldfame.size.height/2-64)),NSValue(cgPoint:CGPoint(x:kSCREEN_WIDTH/2,y:0)),NSValue(cgPoint: CGPoint(x:changeView.centerX,y:changeView.centerY))]
        annimation.duration = 0.5
        annimation.delegate = self
        annimation.isRemovedOnCompletion = false
        annimation.fillMode = kCAFillModeForwards
        showLabel.layer.add(annimation, forKey: "position")
    }
    
    func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
        if flag {
            showLabel.isHidden = true
            changeView.textField.text = viewModel?.selectPrice
            changeView.textField.font = showLabel.font
            changeView.textField.textColor  = (viewModel?.selectStates)! ?  kRedColor : kGreenColor
            self.changeLegalMoney()
        }
    }
    
    @objc func priceKindAction() {
        self.endEditing(true)
        SelectActionManger.manager.creatSheet(style: .commonSty, titleArr: [kText("市价"),kText("限价")], selectStr: limitBtn.nameLabel.text, dataSource: self)
        SelectActionManger.manager.select?.tag = 2000
    }
    
    
    
    /// 选择小数位数
    @objc func selectDigit() {
        self.endEditing(true)
        let arr = viewModel?.archiveDigitArr()
        if arr?.count == 0 {
            return
        }
        SelectActionManger.manager.creatSheet(style: .commonSty, titleArr: arr!, selectStr: viewModel?.digit, dataSource: self)
        SelectActionManger.manager.select?.tag = 1000
    }
    
    
    /// 买入
    @objc func buyBtnAction(_ isNeedRefreshAsset:Bool = false) {
        selectNumber.isBuyBool = true
        riseBtn.backgroundColor = kGreenColor
      self.changeStyle(selectIndex: 0)
      viewModel?.selectPrice = ""
        self.viewModel?.changePair = true
        if !isNeedRefreshAsset {
      viewModel?.archiveInformation()
        }else {
      viewModel?.assetBool = true
        }
      viewModel?.changeFirst(states: true)
      viewModel?.refreshBool = true
      
    }
    ///卖出
    @objc func sellAction(_ isNeedRefreshAsset:Bool = true) {
        selectNumber.isBuyBool = false
        riseBtn.backgroundColor = kRedColor
        self.changeStyle(selectIndex: 1)
        self.viewModel?.changePair = true
        viewModel?.selectPrice = ""
        if !isNeedRefreshAsset {
        viewModel?.archiveInformation()
        }else {
            viewModel?.assetBool = true
        }
        viewModel?.changeFirst(states: true)
        viewModel?.refreshBool = true
    }
    
    //获取买入最小价格
    func archiveSmallPric() {
        let price = viewModel?.archiveSmallPrice()
        changeView.textField.text = price
        changeView.textField.textColor  = (viewModel?.selectStates)! ?  kRedColor : kGreenColor
    }
    //获取卖出最大价格
    func archiveBigPrice() {
        let price = viewModel?.archiveBigPrice()
        changeView.textField.text = price
        changeView.textField.textColor  = (viewModel?.selectStates)! ? kRedColor : kGreenColor
    }
    //修改数字货币对应的法币价格
    func changeLegalMoney()  {
        viewModel?.archiveBigNumber()
        if (viewModel?.isMarketBool)! && !(viewModel?.selectStates)!  {
            kindPrice.text = String(format: "%@%@",(viewModel?.coinBigNumber)!,APPTransactionPair.default.selectPairModel.name
                .components(separatedBy: "/").last!)
        }else {
            
            kindPrice.text = String(format: "%@%@",(viewModel?.coinBigNumber)!,APPTransactionPair.default.selectPairModel.name
                .components(separatedBy: "/").first!)
        }
        
        
        if changeView.textField.text?.count != 0 {
            currentMoney.text = viewModel?.archiveLeveMoeny(coin: changeView.textField.text!)
            self.changeSliderPrice()
        }else {
            currentMoney.text = ""
            if !(viewModel?.isMarketBool)! && !(viewModel?.selectStates)! {
                kindPrice.text = ""
            }
        }
    }
    
    func changeStyle(selectIndex:Int) -> Void {
        buyBtnArr.enumerateObjects { (sender, index, stop) in
            let btn = sender as AnyObject as! UIButton
            viewModel?.selectStates = selectIndex == 0 ? false : true
            if selectIndex == index {
                btn.backgroundColor = selectIndex == 0 ? kGreenColor : kRedColor
                btn.themeSetTitleColor(ThemeManager.ThemeColorKeys.btnText, for: UIControlState.normal)
            }else {
                btn.backgroundColor = UIColor.clear
                btn.themeSetTitleColor(ThemeManager.ThemeColorKeys.text2, for: UIControlState.normal)
            }
        }
    }
    
    // MARK: - 按钮添加
    @objc func addBtnAction() {
        changeView.textField.text = viewModel?.addPrice()
        self.changeLegalMoney()
    }
    
    @objc func subBtnAction() {
        changeView.textField.text = viewModel?.minus()
        self.changeLegalMoney()
    }
    
    // MARK: - SelectmangerDelegate  切换小数位数  限价  市价
    func selectModel(model: SheetModel) {
        if SelectActionManger.manager.select?.tag == 1000 {
            viewModel?.digit = model.selectStr
            digitBtn.nameLabel.text = String(format: "%@%@",kText("小数位数"),model.selectStr!)
            viewModel?.changeCalculationPrice(digit: Int(model.selectStr!)!)
            self.viewModel?.changePair = true
            viewModel?.refreshBool = true
            if viewModel?.currentData != nil {
                viewModel?.changeDepth(data: (viewModel?.currentData)!)
            }
        }else if SelectActionManger.manager.select?.tag == 2000 {
        limitBtn.nameLabel.text = model.selectStr
        if model.selectStr == kText("市价") {
          viewModel?.isMarketBool = true
         self.changeStates(marketBool: true)
        }else{
            viewModel?.isMarketBool = false
            self.changeStates()
          }
        }
        self.viewModel?.changePair = true
        viewModel?.refreshBool = true
         SelectActionManger.manager.close()
    }
    
    func changeStates(marketBool:Bool = false)  {
        if marketBool {
            changeView.isHidden = true
            currentMoney.isHidden = true
            optimalLabel.isHidden = false
        }else {
            changeView.isHidden = false
            currentMoney.isHidden = false
            optimalLabel.isHidden = true
        }
        
    }
    
    func changeCurrentPrice() {
        let model = viewModel!.currentPairModel
        let digit = viewModel?.digit ?? "6"
        self.priceBtn.setTitle(CYCalculate.cy_intercept(number: model.price, digit: Int(digit)!), for: UIControlState.normal)
        if model.price > 0 {
            let open = model.open == 0 ? 1 : model.open
            let increase = (model.price - model.open) * 100 / open
            if increase >= 0 {
                self.priceBtn.setTitleColor(kGreenColor, for: UIControlState.normal)
            }else {
                self.priceBtn.setTitleColor(kRedColor, for: UIControlState.normal)
            }
        }else {
            self.priceBtn.setTitle("0.00", for: UIControlState.normal)
            priceBtn.themeSetTitleColor(ThemeManager.ThemeColorKeys.text3, for: UIControlState.normal)
        }
        let moneyStr = String(format: "%.2f", model.money)
        if AppCacheInfo.default.currency == "USD" {
            moneyBtn.setTitle("≈$ \(moneyStr)", for: UIControlState.normal)
        }else {
            moneyBtn.setTitle("≈￥ \(moneyStr)", for: UIControlState.normal)
        }
    }
    
    
    /// 修改币币交易 选择后对应的展示
    func changeCoin()  {
        numberView.textField.text = ""
        if (viewModel?.isPairBool)! {
            if (viewModel?.isMarketBool)! && !(viewModel?.selectStates)! {
                numberView.addBtn.setTitle(APPTransactionPair.default.selectPairModel.name
                    .components(separatedBy: "/").last, for: UIControlState.normal)
                numberView.textField.placeholder = kText("交易额")
            }else {
            numberView.addBtn.setTitle(APPTransactionPair.default.selectPairModel.name
                .components(separatedBy: "/").first, for: UIControlState.normal)
                numberView.textField.placeholder = kText("数量")
            }
          changeView.textField.text = ""
          
            kindPrice.text = ""
            if AppInfo.default.isLogin {
                var coinName = viewModel?.tradeCoin ?? ""
                if AppCacheInfo.default.isEnlish {
                   coinName =  " " + coinName
                }
                let title = String(format:"%@%@",(viewModel?.selectStates)! ? kText("卖出") : kText("买入"),coinName)
            riseBtn.setTitle(title, for: UIControlState.normal)
            }else {
                self.riseBtn.setTitle(kText("登录"), for: UIControlState.normal)
            }
            tradeLabel.text = kText("交易额") + "---"
            selectNumber.showSlider(x: 0)
        }else {
            tradeLabel.text = kText("交易额") + "---"
            selectNumber.showSlider(x: 0)
            if AppInfo.default.isLogin {
                riseBtn.setTitle(String(format:"%@",(viewModel?.selectStates)! ? kText("卖出") : kText("买入")), for: UIControlState.normal)
            }else {
                self.riseBtn.setTitle(kText("登录"), for: UIControlState.normal)
            }
            changeView.textField.text = ""
            kindPrice.text = ""
            if (viewModel?.isMarketBool)! && !(viewModel?.selectStates)! {
                numberView.textField.placeholder = kText("交易额")
            }else {
                numberView.textField.placeholder = kText("数量")
            }
        }
        if (viewModel?.isMarketBool)!  {
            tradeLabel.isHidden = true
        }else {
            tradeLabel.isHidden = false
        }
    }
    
    
    @objc func sliderAction() {
        
    }
    
    @objc func riseBtnAction() {
        self.endEditing(true)
        if !AppInfo.default.isLogin {
            self.viewModel?.controller?.navigationController?.pushViewController(LoginViewController(), animated: true)
            return
        }
        if !(viewModel?.isPairBool)! {
            CYMBShow.showMessage(kText("请选择交易对"))
            return
        }
        if (viewModel?.isMarketBool)! {
            if (viewModel?.selectStates)! {
                if self.viewModel?.depModel?.deptDownArr.count == 0 {
                    CYMBShow.showMessage(kText("当前无行情,不支持市价交易"))
                    return
                }
            }else {
                if self.viewModel?.depModel?.depUpArr.count == 0 {
                    CYMBShow.showMessage(kText("当前无行情,不支持市价交易"))
                    return
                }
            }
            
        }
        
        //限价处理单价价格
        if !(viewModel?.isMarketBool)! {
            if !(viewModel?.checkLimitPrice())! {
                return
            }
        }
        if viewModel?.cashNumber.count == 0 {
            CYMBShow.showMessage(kText("请输入下单数量"))
            return
        }
        if Double(viewModel!.cashNumber) == 0.00 {
            CYMBShow.showMessage(kText("下单数量不能为0"))
            return
        }
        if numberView.textField.text!.count == 0 {
            CYMBShow.showMessage(kText("请输入下单数量"))
            return
        }
        if !(viewModel?.selectStates)! && !(viewModel?.isMarketBool)!{
        if Double(viewModel!.totalTradeMoney)! > (viewModel?.coinAssetModel.currentAmount)! {
            CYMBShow.showMessage(kText("您的交易额不足,请先充值"))
            return
        }
        }else {
            if Double(viewModel!.cashNumber)! > (viewModel?.coinAssetModel.currentAmount)! {
                CYMBShow.showMessage(kText("您的交易额不足,请先充值"))
                return
            }
            
        }
        if !AppSecurityInfo.default.model.isTradePwd {
            CYMBShow.showMessage(kText("请先设置交易密码"))
            return
        }
        
        GooglePassWordManager.creatGoolPassWord(dataSource: self, style: googleStyle.googlePassWordStyle)
    }
    
    @objc func allBtnAction() {
        if !AppInfo.default.isLogin {
            self.dataSource.controller?.navigationController?.pushViewController(LoginViewController(), animated: true)
            return
        }
        
        controller = CurrencyOrderViewController()
        controller?.viewModel?.currentArr = (viewModel?.coinOrderArr)!
        controller?.hidesBottomBarWhenPushed = true
        self.viewModel?.controller?.navigationController?.pushViewController(controller!, animated: true)
    }
    deinit {
        dataSource.removeObserver(self, forKeyPath: "refreshBool", context: nil)
        dataSource.removeObserver(self, forKeyPath: "assetBool", context: nil)
        dataSource.removeObserver(self, forKeyPath: "changePair", context: nil)
        dataSource.removeObserver(self, forKeyPath: "coinOrder",context: nil)
    }
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}

extension CurrencyExchangeView:UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange,
                   replacementString string: String) -> Bool {
        if string.count == 0 {
            return true
        }
        if textField.isEqual(numberView.textField) {
        let digit = self.viewModel?.archiveDigitNumber(isNumber:true,isTradeAmount:false)
        return textField.cheakNumberFormat(digit: digit!, range: range, string: string, interger: 8)
        }else {
            return textField.cheakNumberFormat(digit: (viewModel?.regularModel.priceDigit)!, range: range, string: string, interger: 8)
        }
    }
    
    @objc func textFieldDidChangeValue(textField:UITextField) {
        if textField.isEqual(changeView.textField) {
        viewModel?.changePrice(price: textField.text!)
        self.changeLegalMoney()
        }else {
            viewModel?.cashNumber = textField.text!
           tradeLabel.text = viewModel?.calculateTradeMoney()
        }
        
    }
    
    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        let view = super.hitTest(point, with: event)
        if (view?.isKind(of: SelectNumberView.self))! {
            entrustTableView.isScrollEnabled = false
        }else {
            entrustTableView.isScrollEnabled = true
        }
        return view
    }
}

extension CurrencyExchangeView:SelectNumberDelegate,GoolPassWordDelegate {
    func googleVerificationt(passWord: String) {
        if passWord.count < 6 {
            CYMBShow.showMessage(kText("交易密码错误"))
            return
        }
        viewModel?.passWord = passWord
        self.viewModel?.tradeOrder()
    }
    
    func changeSlider(value: Double) {
        viewModel?.value = value
        if value == 0 {
            numberView.textField.text = ""
            return
        }
        if Double(viewModel!.coinBigNumber) == 0 {
            numberView.textField.text = ""
            return
        }
        let digit = self.viewModel?.archiveDigitNumber(isNumber:true,isTradeAmount:false)
        let number = CYCalculate.cy_multiplying(firstNumber: viewModel!.coinBigNumber, lastNumber: (viewModel?.value)!, digit: digit!)
        numberView.textField.text = number == "0" ? "" : number
        self.changeSliderPrice()
    }
    
    func changeSliderPrice()  {
        if numberView.textField.text?.count == 0 {
            return
        }
        viewModel?.cashNumber = numberView.textField.text!
        tradeLabel.text = viewModel?.calculateTradeMoney()
    }
}

extension CurrencyExchangeView:EntrustCellDelegate {
    func changeStates(_ model: CoinOrderModel) {
        viewModel?.selectOrderModel =  model
        if model.status == 0 || model.status == 1 || model.status == 3 || model.status == 5{
            viewModel?.cancelOrder()
        }
    }
}
